package com.dlwx.parttimetalent.fragment.master;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.dlwx.parttimetalent.R;
import com.dlwx.parttimetalent.adapter.OrderMasterAdapter;
import com.dlwx.parttimetalent.bean.OrderBean;
import com.dlwx.parttimetalent.comm.Constant;
import com.dlwx.parttimetalent.comm.Http;
import com.dlwx.parttimetalent.inter.PositionInter;
import com.dlwx.parttimetalent.ui.OrderDetailActivity;
import com.dlwx.parttimetalent.utils.DealResult;
import com.dlwx.parttimetalent.utils.OkgoUtil;
import com.dlwx.parttimetalent.utils.ToastUtils;
import com.github.jdsjlzx.ItemDecoration.DividerDecoration;
import com.github.jdsjlzx.interfaces.OnItemClickListener;
import com.github.jdsjlzx.interfaces.OnLoadMoreListener;
import com.github.jdsjlzx.interfaces.OnRefreshListener;
import com.github.jdsjlzx.recyclerview.LRecyclerView;
import com.github.jdsjlzx.recyclerview.LRecyclerViewAdapter;
import com.google.gson.reflect.TypeToken;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;


public class MasterOneFragment extends Fragment {
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";
    @BindView(R.id.recyclerView)
    LRecyclerView recyclerView;
    Unbinder unbinder;

    private String mParam1;
    private String mParam2;

    private OnFragmentInteractionListener mListener;

    private OrderMasterAdapter mAdapter;
    private int orderStatus;
    private int page=1;
    private LRecyclerViewAdapter lRecyclerViewAdapter;

    public MasterOneFragment() {
    }

    public static MasterOneFragment newInstance(String param1, String param2) {
        MasterOneFragment fragment = new MasterOneFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        orderStatus=getArguments().getInt("type");
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_master_one, container, false);
        unbinder = ButterKnife.bind(this, view);
        return view;
    }

    @Override
    public void onStart() {
        super.onStart();
        initView();
        refresh();
    }
    private void getDatas() {
        OkgoUtil.post(Http.hireOrderList,getActivity())
                .params("orderStatus",orderStatus)
                .params("pageno",page)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        OrderBean parentBean= DealResult.getInstance().dealDatas(getActivity(),response,new TypeToken<OrderBean>() {}.getType());
                        if(parentBean==null){return;}
                        int code=parentBean.getCode();
                        if(code== Constant.SUCESS||code==Constant.EMPTY){
                            setDatas(parentBean.getBody());
                        }else {
                            ToastUtils.toastForShort(getActivity(),parentBean.getResult());
                        }
                    }
                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        recyclerView.refreshComplete(mAdapter.getItemCount());
                        ToastUtils.toastForShort(getActivity(),getString(R.string.bad_net));
                    }
                });
    }

    private void setDatas(List<OrderBean.BodyBean> body) {
        if(recyclerView==null){return;}
        if(body.isEmpty()){
            recyclerView.setNoMore(true);
        }else{
            mAdapter.addAll(body);
            recyclerView.refreshComplete(mAdapter.getItemCount());
        }
    }

    private void initView() {
        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        mAdapter = new OrderMasterAdapter(getActivity(), new PositionInter() {
            @Override
            public void callBack(int position) {
                refresh();
            }
        });
        mAdapter.setDataList(new ArrayList<OrderBean.BodyBean>());
         lRecyclerViewAdapter = new LRecyclerViewAdapter(mAdapter);
        //divider
        DividerDecoration divider = new DividerDecoration.Builder(getActivity())
                .setHeight(R.dimen.size_1)
//                .setPadding(R.dimen.divider_padding)
                .setColorResource(R.color.bg)
                .build();
        recyclerView.setHasFixedSize(true);
        recyclerView.addItemDecoration(divider);
        recyclerView.setAdapter(lRecyclerViewAdapter);
        recyclerView.setLoadMoreEnabled(true);
        recyclerView.setPullRefreshEnabled(true);
        recyclerView.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh() {
                refresh();
            }
        });
        recyclerView.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore() {
                page++;
                getDatas();
            }
        });
        lRecyclerViewAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                int orderId=mAdapter.getDataList().get(position).getOrderid();
                Intent i=new Intent(getActivity(), OrderDetailActivity.class);
                i.putExtra("id",orderId+"");
                i.putExtra("orderType","1");
                startActivity(i);
            }
        });
    }

    // TODO: Rename method, update argument and hook method into UI event
    public void onButtonPressed(Uri uri) {
        if (mListener != null) {
            mListener.onFragmentInteraction(uri);
        }
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof OnFragmentInteractionListener) {
            mListener = (OnFragmentInteractionListener) context;
        } else {
//            throw new RuntimeException(context.toString() + " must implement OnFragmentInteractionListener");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        OkGo.getInstance().cancelTag(this);
    }

    public interface OnFragmentInteractionListener {
        void onFragmentInteraction(Uri uri);
    }

    private void refresh(){
        page=1;
        mAdapter.clear();
        lRecyclerViewAdapter.notifyDataSetChanged();
        getDatas();
    }
}
